package com.hashnode.mybatisreverse.controller;

import com.hashnode.mybatisreverse.model.Student;
import com.hashnode.mybatisreverse.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

//@RestController //相当于控制层类上加@Controller + 方法上加@ResponseBody,意味着当前控制层返回的都是JSON对象
//@Controller
//@RestController
@Controller
//@RequestMapping("student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    //如果没有指定方法,则该方法支持GET和POST请求
    // 也可以用 @GetMapping   @PostMapping等
    // @GetMapping 查询
    // @PostMapping 新增
    // @DeleteMapping 删除
    // @PutMapping  相当于update(修改)
    @RequestMapping(value = "query",method = RequestMethod.POST)
    public @ResponseBody Object query(){
        Student student = studentService.queryStudentById(1);
        return student;
    }

    @RequestMapping(value = "queryById")
    public @ResponseBody Object queryById(Integer id){
        Student student = studentService.queryStudentById(id);
        return student;
    }

    @RequestMapping(value = "update")
    public @ResponseBody Object update(Integer id,String name){
        Student student = new Student();
        student.setId(id);
        student.setName(name);

        studentService.updateStudentById(student);

        return studentService.queryStudentById(id);
    }

    @RequestMapping(value = "updateObj")
    public @ResponseBody Object update(Student student){
        studentService.updateStudentById(student);

        if(student.getId() != null){
            return studentService.queryStudentById(student.getId());
        }
        else {
            return null;
        }
    }

//    @RequestMapping(value = "/reststudent/{id}/{age}")
    @GetMapping(value = "/reststudent/{id}/{age}")
    public @ResponseBody Object restStudent(@PathVariable("id")Integer id,@PathVariable("age")Integer age){
        Map<String,Object> retMap = new HashMap<>();

        retMap.put("id",id);
        retMap.put("age",age);
        return retMap;
    }

    //以下代码restStudent2会和restStudent1出现路径混淆的问题,通常在restful风格中方法的请求方式会按增删查改的请求方式来区分
    @PostMapping(value = "/reststudent/{id}/{postStatus}")
    public @ResponseBody Object restStudent2(@PathVariable("id")Integer id,@PathVariable("postStatus")Integer postStatus){
        Map<String,Object> retMap = new HashMap<>();

        retMap.put("id",id);
        retMap.put("postStatus",postStatus);
        return retMap;
    }

    @GetMapping(value = "/sayhello")
    public ModelAndView sayHello(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","Hello!");
        mv.setViewName("hello");
        return mv;
    }

}
